package com.ipan.kits.log4j;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Pattern;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ipan.kits.base.ExceptionUtil;
import com.ipan.kits.time.DateFormatUtil;
/**
 * 
 * 滚动日志自清理版
 * 
 * 按日期滚动日志，自动清理过期日志；避免人工干预服务器的日志维护，也不需要启动定时任务定期清理，节省服务器资源；
 * 
 * 清理策略：
 * 根据maxSaveDays设置来定制保存天数，以系统当前时间减去maxSaveDays来确定需要删除的日志文件；
 * 在每次文件滚动的时候，顺便删除过期日志；
 * 
 * 注意事项：
 * datePattern不能修改，使用默认的'.'yyyy-MM-dd格式；
 * 
 * 参考：
 * org.apache.log4j.DailyRollingFileAppender
 * 
 * @author iPan
 * @date 2021-12-10
 */
public class MyDailyRollingFileAppender extends FileAppender {

	private static Logger logger = LoggerFactory.getLogger(MyDailyRollingFileAppender.class); // 使用系统默认Logger输出日志
	protected int  maxSaveDays = 30; // 默认保存30天，0表示不做任何清理；
								   // 注意log4j的字段类型不能使用包装类型，只能使用基础类型；

	// The code assumes that the following constants are in a increasing
	// sequence.
	static final int TOP_OF_TROUBLE = -1;
	static final int TOP_OF_MINUTE = 0;
	static final int TOP_OF_HOUR = 1;
	static final int HALF_DAY = 2;
	static final int TOP_OF_DAY = 3;
	static final int TOP_OF_WEEK = 4;
	static final int TOP_OF_MONTH = 5;

	private static final String DATE_PATTERN_REGEX = "^.+\\.log\\.\\d{4}-\\d{2}-\\d{2}$"; 
	private static final String DEFAULT_DATE_PATTERN = "'.'yyyy-MM-dd";
	/**
	   The date pattern. By default, the pattern is set to
	   "'.'yyyy-MM-dd" meaning daily rollover.
	 */
	private String datePattern = DEFAULT_DATE_PATTERN; // 写死，不能修改！文件删除根据这个模式来匹配，所以，不能修改！
	
	/**
	   The log file will be renamed to the value of the
	   scheduledFilename variable when the next interval is entered. For
	   example, if the rollover period is one hour, the log file will be
	   renamed to the value of "scheduledFilename" at the beginning of
	   the next hour. 
	
	   The precise time when a rollover occurs depends on logging
	   activity. 
	*/
	private String scheduledFilename;

	/**
	   The next time we estimate a rollover should occur. */
	private long nextCheck = System.currentTimeMillis() - 1;

	Date now = new Date();

	SimpleDateFormat sdf;

	RollingCalendar rc = new RollingCalendar();

	int checkPeriod = TOP_OF_TROUBLE;

	// The gmtTimeZone is used only in computeCheckPeriod() method.
	static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

	/** The default constructor does nothing. */
	public MyDailyRollingFileAppender() {
	}

	/**
     * Instantiate a <code>DailyRollingFileAppender</code> and open the
     * file designated by <code>filename</code>. The opened filename will
     * become the ouput destination for this appender.
    */
	public MyDailyRollingFileAppender (Layout layout, String filename) throws IOException {
	    super(layout, filename, true);
//	    this.datePattern = datePattern;
	    activateOptions();
	}

	/**
	   The <b>DatePattern</b> takes a string in the same format as
	   expected by {@link SimpleDateFormat}. This options determines the
	   rollover schedule.
	 */
	public void setDatePattern(String pattern) {
		datePattern = pattern;
	}

	/** Returns the value of the <b>DatePattern</b> option. */
	public String getDatePattern() {
		return datePattern;
	}

	public void activateOptions() {
		super.activateOptions();
		if (datePattern != null && fileName != null) {
			now.setTime(System.currentTimeMillis());
			sdf = new SimpleDateFormat(datePattern);
			int type = computeCheckPeriod();
			printPeriodicity(type);
			rc.setType(type);
			File file = new File(fileName);
			scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));

		} else {
			LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
		}
	}

	void printPeriodicity(int type) {
		switch (type) {
		case TOP_OF_MINUTE:
			LogLog.debug("Appender [" + name + "] to be rolled every minute.");
			break;
		case TOP_OF_HOUR:
			LogLog.debug("Appender [" + name + "] to be rolled on top of every hour.");
			break;
		case HALF_DAY:
			LogLog.debug("Appender [" + name + "] to be rolled at midday and midnight.");
			break;
		case TOP_OF_DAY:
			LogLog.debug("Appender [" + name + "] to be rolled at midnight.");
			break;
		case TOP_OF_WEEK:
			LogLog.debug("Appender [" + name + "] to be rolled at start of week.");
			break;
		case TOP_OF_MONTH:
			LogLog.debug("Appender [" + name + "] to be rolled at start of every month.");
			break;
		default:
			LogLog.warn("Unknown periodicity for appender [" + name + "].");
		}
	}

	// This method computes the roll over period by looping over the
	// periods, starting with the shortest, and stopping when the r0 is
	// different from from r1, where r0 is the epoch formatted according
	// the datePattern (supplied by the user) and r1 is the
	// epoch+nextMillis(i) formatted according to datePattern. All date
	// formatting is done in GMT and not local format because the test
	// logic is based on comparisons relative to 1970-01-01 00:00:00
	// GMT (the epoch).

	int computeCheckPeriod() {
		RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.getDefault());
		// set sate to 1970-01-01 00:00:00 GMT
		Date epoch = new Date(0);
		if (datePattern != null) {
			for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
				simpleDateFormat.setTimeZone(gmtTimeZone); // do all date formatting in GMT
				String r0 = simpleDateFormat.format(epoch);
				rollingCalendar.setType(i);
				Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
				String r1 = simpleDateFormat.format(next);
				// System.out.println("Type = "+i+", r0 = "+r0+", r1 = "+r1);
				if (r0 != null && r1 != null && !r0.equals(r1)) {
					return i;
				}
			}
		}
		return TOP_OF_TROUBLE; // Deliberately head for trouble...
	}

	/**
	   Rollover the current file to a new file.
	*/
	void rollOver() throws IOException {

		/* Compute filename, but only if datePattern is specified */
		if (datePattern == null) {
			errorHandler.error("Missing DatePattern option in rollOver().");
			return;
		}

		String datedFilename = fileName + sdf.format(now);
		// It is too early to roll over because we are still within the
		// bounds of the current interval. Rollover will occur once the
		// next interval is reached.
		if (scheduledFilename.equals(datedFilename)) {
			return;
		}

		// close current file, and rename it to datedFilename
		this.closeFile();

		File target = new File(scheduledFilename);
		if (target.exists()) {
			target.delete();
		}

		File file = new File(fileName);
		boolean result = file.renameTo(target);
		if (result) {
			LogLog.debug(fileName + " -> " + scheduledFilename);
		} else {
			LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
		}

		try {
			// This will also close the file. This is OK since multiple
			// close operations are safe.
			this.setFile(fileName, true, this.bufferedIO, this.bufferSize);
		} catch (IOException e) {
			errorHandler.error("setFile(" + fileName + ", true) call failed.");
		}
		scheduledFilename = datedFilename;
		
		// 删除过期日志文件
		deleteOldFiles();
	}

	/**
	 * This method differentiates DailyRollingFileAppender from its
	 * super class.
	 *
	 * <p>Before actually logging, this method will check whether it is
	 * time to do a rollover. If it is, it will schedule the next
	 * rollover time and then rollover.
	 * */
	protected void subAppend(LoggingEvent event) {
		long n = System.currentTimeMillis();
		if (n >= nextCheck) {
			now.setTime(n);
			nextCheck = rc.getNextCheckMillis(now);
			try {
				rollOver();
			} catch (IOException ioe) {
				if (ioe instanceof InterruptedIOException) {
					Thread.currentThread().interrupt();
				}
				LogLog.error("rollOver() failed.", ioe);
			}
		}
		super.subAppend(event);
	}

	public int getMaxSaveDays() {
		return maxSaveDays;
	}

	public void setMaxSaveDays(int maxSaveDays) {
		this.maxSaveDays = maxSaveDays;
	}

	public void deleteOldFiles() {
		File[] files = getAllOldLogs();
		if (files == null || files.length < 1) {
			return ;
		}
		for (File f : files) {
			if (f.exists()) {
				boolean result = f.delete();
				if (result) {
					logger.info("清理过期日志{}，成功。", f.getName());
				} else {
					logger.info("清理过期日志{}，失败。", f.getName());
				}
			}
		}
	}
	protected File[] getAllOldLogs() {
		if (maxSaveDays < 1) {
			return null;
		}
		final File file = new File(fileName);
		File logPath = file.getParentFile();
		if (logPath == null) {
			logPath = new File(".");
		}

		File[] retFiles = logPath.listFiles(new FileFilter() {
			public boolean accept(File file) {
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DAY_OF_MONTH, -1 * maxSaveDays);
				Date cutOffTime = null;
				try {
					cutOffTime = DateFormatUtil.parseDate("yyyy-MM-dd", DateFormatUtil.formatDate("yyyy-MM-dd", cal.getTime()));
				} catch (ParseException e1) {
					ExceptionUtil.wrapRuntime(e1);
				}
				
				String fname = file.getName();
				boolean matches = Pattern.matches(DATE_PATTERN_REGEX, fname);
				if (matches) {
					try {
						Date date = DateFormatUtil.parseDate("yyyy-MM-dd", fname.substring(fname.length() - 10));
						boolean isOldFile = date.getTime() < cutOffTime.getTime();
						return isOldFile;
					} catch (ParseException e) {
						return false;
					}
				}
				return false;
			}
		});
		return retFiles;
	}

}

/**
 *  RollingCalendar is a helper class to DailyRollingFileAppender.
 *  Given a periodicity type and the current time, it computes the
 *  start of the next interval.  
 */
class RollingCalendar extends GregorianCalendar {
	private static final long serialVersionUID = -3560331770601814177L;

	int type = MyDailyRollingFileAppender.TOP_OF_TROUBLE;

	RollingCalendar() {
		super();
	}

	RollingCalendar(TimeZone tz, Locale locale) {
		super(tz, locale);
	}

	void setType(int type) {
		this.type = type;
	}

	public long getNextCheckMillis(Date now) {
		return getNextCheckDate(now).getTime();
	}

	public Date getNextCheckDate(Date now) {
		this.setTime(now);

		switch (type) {
		case MyDailyRollingFileAppender.TOP_OF_MINUTE:
			this.set(Calendar.SECOND, 0);
			this.set(Calendar.MILLISECOND, 0);
			this.add(Calendar.MINUTE, 1);
			break;
		case MyDailyRollingFileAppender.TOP_OF_HOUR:
			this.set(Calendar.MINUTE, 0);
			this.set(Calendar.SECOND, 0);
			this.set(Calendar.MILLISECOND, 0);
			this.add(Calendar.HOUR_OF_DAY, 1);
			break;
		case MyDailyRollingFileAppender.HALF_DAY:
			this.set(Calendar.MINUTE, 0);
			this.set(Calendar.SECOND, 0);
			this.set(Calendar.MILLISECOND, 0);
			int hour = get(Calendar.HOUR_OF_DAY);
			if (hour < 12) {
				this.set(Calendar.HOUR_OF_DAY, 12);
			} else {
				this.set(Calendar.HOUR_OF_DAY, 0);
				this.add(Calendar.DAY_OF_MONTH, 1);
			}
			break;
		case MyDailyRollingFileAppender.TOP_OF_DAY:
			this.set(Calendar.HOUR_OF_DAY, 0);
			this.set(Calendar.MINUTE, 0);
			this.set(Calendar.SECOND, 0);
			this.set(Calendar.MILLISECOND, 0);
			this.add(Calendar.DATE, 1);
			break;
		case MyDailyRollingFileAppender.TOP_OF_WEEK:
			this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
			this.set(Calendar.HOUR_OF_DAY, 0);
			this.set(Calendar.MINUTE, 0);
			this.set(Calendar.SECOND, 0);
			this.set(Calendar.MILLISECOND, 0);
			this.add(Calendar.WEEK_OF_YEAR, 1);
			break;
		case MyDailyRollingFileAppender.TOP_OF_MONTH:
			this.set(Calendar.DATE, 1);
			this.set(Calendar.HOUR_OF_DAY, 0);
			this.set(Calendar.MINUTE, 0);
			this.set(Calendar.SECOND, 0);
			this.set(Calendar.MILLISECOND, 0);
			this.add(Calendar.MONTH, 1);
			break;
		default:
			throw new IllegalStateException("Unknown periodicity type.");
		}
		return getTime();
	}
	
}
